<template>
  <div>
    <!-- 面包屑 导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 用作用于插槽来显示当前状态 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- 注释：用作用域插槽会把上面prop属性覆盖所以可以把prop删除 -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 用作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 内容主体区域 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <!-- 用户 -->
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户列表区域 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="70px">
        <el-form-item label="用户名">
          <!-- 修改用户名 -->
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="email">
          <!-- 修改密码 -->
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <!-- 修改密码 -->
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRoleDialogVisible" width="50%">
      <div>
        <p>当前用户:{{userInfo.username}}</p>
        <p>当前角色:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { async } from "q";
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      // 判断值是否正确
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表的数据参数对象
      queryInfo: {
        query: "",
        // 当前页
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      userlist: [],
      total: 0,
      //   控制对话框的显示与隐藏
      addDialogVisible: false,
      //    控制对话框修改的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editFrom: {},
      //   用户添加表单数据
      addForm: {
        username: "",
        password: ""
      },
      //   表单验证
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 修改
      editFrom: {},
      // 验证表单修改规则
      editFromRules: {
        // 邮箱验证
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        // 手机号验证
        mobile: [
          { required: true, message: "请输入用户手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 控制分配角色的显示隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据
      roleList: [],
      // 已经选中的id值
      selectedRoleId:''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // 打印当前页数
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听swich开关状态的改变
    async userStateChange(userInfo) {
      // 打印当前的状态 值 fale ture
      // 打印是一个对象形式
      // console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      //  console.log(res)
      if (res.meta.status !== 200) {
        //  失败则重置 则取反
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 用户添加重置
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 修改用户重置
    editDialogClosed() {
      this.$refs.editFromRef.resetFields();
    },
    editUserInfo() {
      this.$refs.addFormRef.validate(async valid => {
        // 判断用户是否填写正确
        // console.log(valid);
        // 判断用户是否正确并发送请求
        if (!valid) return;
        //正确并发送发送添加网络请求
        const { data: res } = await this.$http.post("users", this.addForm);
        // 判断发送的状态码
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加成功");
        // 隐藏添加用户的对话框
        this.addDialogVisible = false;
        // 调用并重新获取用户列表
        this.getUserList();
      });
    },
    async showEditDialog(id) {
      // 打印相对应的id值
      // console.log(id);
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户列表失败");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFromRef.validate(async valid => {
        // // 判断用户是否填写正确
        // console.log(valid);
        // 错误 返回
        if (!valid) return;
        // 正确发送请求 并修改
        const { data: res } = await this.$http.put(
          "users/" + this.editFrom.id,
          { email: this.editFrom.email, mobile: this.editFrom.mobile }
        );
        if (res.meta.status !== 201) {
          this.$message.error("修改用户失败");
        }
        this.$message.success("修改用户成功");
        // 隐藏添加用户修改的对话框
        (this.editDialogVisible = false),
          // 调用并重新获取用户修改列表
          this.getUserList();
      });
    },
    // 根据id删除用户
    async removeUserById(id) {
      //打印出删除 的id
      // console.log(id);
      const ress = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // 如果确认删除 则返回值为字符串confirm
      // 如果用户取消删除 则返回值为字符串cancel
      // console.log(ress);
      if (ress !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("用户删除失败");
      }
      this.$message.success("删除用户成功");
      // 刷新列表页
      this.getUserList();
    },
    // 展示分配权限的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;
      // 获取所有 角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roleList = res.data;
      this.setRoleDialogVisible = true;
    },
    // 点击按钮分配权限
    async saveRoleInfo(){
      // console.log(this.selectedRoleId);
      // 判断是否为id的值
      if(!this.selectedRoleId){
        return this.$message.error('请选择要分配的角色')
      }
       // 成功则发送请求获取
   const {data:res} =await this.$http.put(`users/${this.userInfo.id}/role`,
   {rid:this.selectedRoleId})
   if(res.meta.status!==200){
     return this.$message.error('失败')
   }
   this.$message.success('成功')
  //  刷新
  this.getUserList()
  // 获取过后隐藏
  this.setRoleDialogVisible=false
    }
   
  }
};
</script>

<style lang="less" scoped>
</style>